package com.cz.datafetcher.fetcher;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service(value = "BaoJianZFetcher")
public class BaoJianZFetcher implements IFetcher {
    @Autowired
    RestTemplate restTemplate;

    @Override
    public BigDecimal FetchOneData(String key, Date begin, Date end) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String url = "http://121.5.127.123:35215/IOT/hcnz/interface/searchHistoryData"
                    + "?beginTime="+ sdf.format(begin)
                    + "&endTime=" + sdf.format(end)
                    + "&parameterCode=" + key;
            String r = restTemplate.postForEntity(url, null, String.class).getBody();
            JSONObject jo = JSONObject.parseObject(r);
            JSONObject data = jo.getJSONObject("data");
            JSONArray datas = data.getJSONArray("datas");
            String v = datas.get(datas.size() - 1).toString();
            System.out.println(v);
            return new BigDecimal(v);
        }
        catch (Exception e){
            e.printStackTrace();
            return BigDecimal.ZERO;
        }
    }
}
